package cn.iocoder.yudao.module.system.controller.admin.warehouse;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.gold.convert.warehouse.GoldMaterialWarehouseConvert;
import cn.iocoder.yudao.module.system.controller.admin.warehouse.vo.GoldMaterialWarehousePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.warehouse.vo.GoldMaterialWarehouseRespVO;
import cn.iocoder.yudao.module.system.controller.admin.warehouse.vo.GoldMaterialWarehouseSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.warehouse.vo.GoldMaterialWarehouseSimpleRespVO;
import cn.iocoder.yudao.module.system.convert.user.UserConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.warehouse.GoldMaterialWarehouseDO;
import cn.iocoder.yudao.module.system.service.warehouse.GoldMaterialWarehouseService;
import io.swagger.v3.oas.annotations.Operation;
import com.mzt.logapi.starter.annotation.LogRecord;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserNickname;

@Tag(name = "管理后台 - 金料仓库")
@RestController
@RequestMapping("/gold/warehouse")
public class GoldMaterialWarehouseController {

    @Resource
    private GoldMaterialWarehouseService service;

    @PostMapping("/create")
    @Operation(summary = "创建金料仓库")
    @PreAuthorize("@ss.hasPermission('gold:material-warehouse:create')")
    @LogRecord(type = "金料仓库", subType = "创建", bizNo = "{{#createReqVO.name}}", 
               extra = "{{#createReqVO}}", success = "创建金料仓库成功")
    public CommonResult<Long> create(@Valid @RequestBody GoldMaterialWarehouseSaveReqVO createReqVO) {
        return success(service.create(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新金料仓库")
    @PreAuthorize("@ss.hasPermission('gold:material-warehouse:update')")
    @LogRecord(type = "金料仓库", subType = "更新", bizNo = "{{#updateReqVO.id}}", success = "更新金料仓库成功")
    public CommonResult<Boolean> update(@Valid @RequestBody GoldMaterialWarehouseSaveReqVO updateReqVO) {
        service.update(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除金料仓库")
    @PreAuthorize("@ss.hasPermission('gold:material-warehouse:delete')")
    @LogRecord(type = "金料仓库", subType = "删除", bizNo = "{{#id}}", success = "删除金料仓库成功")
    public CommonResult<Boolean> delete(@RequestParam("id") Long id) {
        service.delete(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得金料仓库")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:query')")
    public CommonResult<GoldMaterialWarehouseRespVO> get(@RequestParam("id") Long id) {
        GoldMaterialWarehouseDO data = service.get(id);
        return success(convertToRespVO(data));
    }

    @GetMapping("/page")
    @Operation(summary = "金料仓库分页")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:query')")
    public CommonResult<PageResult<GoldMaterialWarehouseRespVO>> page(@Valid GoldMaterialWarehousePageReqVO reqVO) {
        PageResult<GoldMaterialWarehouseDO> pageResult = service.getPage(reqVO);
        // 为空时直接返回空列表 + 总数
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(Collections.emptyList(), pageResult.getTotal()));
        }
        // 手动转换 DO -> VO，确保 teamWarehouseId 字段正确映射
        List<GoldMaterialWarehouseRespVO> list = convertToRespVOList(pageResult.getList());
        return success(new PageResult<>(list, pageResult.getTotal()));
    }

    /**
     * 手动转换 DO 列表为 VO 列表
     */
    private List<GoldMaterialWarehouseRespVO> convertToRespVOList(List<GoldMaterialWarehouseDO> doList) {
        return doList.stream().map(this::convertToRespVO).collect(java.util.stream.Collectors.toList());
    }

    /**
     * 手动转换单个 DO 为 VO
     */
    private GoldMaterialWarehouseRespVO convertToRespVO(GoldMaterialWarehouseDO doObj) {
        GoldMaterialWarehouseRespVO vo = new GoldMaterialWarehouseRespVO();
        vo.setId(doObj.getId());
        vo.setCode(doObj.getCode());
        vo.setName(doObj.getName());
        vo.setType(doObj.getType());
        vo.setTeamId(doObj.getTeamId());
        vo.setUserId(doObj.getUserId());
        vo.setTeamWarehouseId(doObj.getTeamWarehouseId()); // 确保这个字段正确映射

        vo.setBalance(doObj.getBalance());
        vo.setResponsiblePerson(doObj.getResponsiblePerson());
        vo.setStatus(doObj.getStatus());
        vo.setTenantId(doObj.getTenantId());
        vo.setCreator(doObj.getCreator());
        vo.setCreateTime(doObj.getCreateTime());
        vo.setUpdater(doObj.getUpdater());
        vo.setUpdateTime(doObj.getUpdateTime());
        return vo;
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出金料仓库 Excel")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:export')")
    public void exportExcel(@Valid GoldMaterialWarehousePageReqVO reqVO, HttpServletResponse response) throws Exception {
        PageResult<GoldMaterialWarehouseDO> page = service.getPage(reqVO);
        List<GoldMaterialWarehouseRespVO> list = convertToRespVOList(page.getList());
        ExcelUtils.write(response, "金料仓库.xls", "数据", GoldMaterialWarehouseRespVO.class, list);
    }

    @GetMapping("/transfer-options")
    @Operation(summary = "查询调拨仓库选项")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:query')")
    public CommonResult<List<GoldMaterialWarehouseRespVO>> getTransferOptions(
            @RequestParam(required = false) Long excludeWarehouseId,
            @RequestParam(required = false) String warehouseTypes) {
        List<Integer> warehouseTypesList = null;
        if (warehouseTypes != null && !warehouseTypes.trim().isEmpty()) {
            warehouseTypesList = Arrays.stream(warehouseTypes.split(","))
                    .map(String::trim)
                    .map(Integer::parseInt)
                    .collect(java.util.stream.Collectors.toList());
        }
        List<GoldMaterialWarehouseDO> warehouses = service.getTransferOptions(excludeWarehouseId, warehouseTypesList);

        List<GoldMaterialWarehouseRespVO> list = convertToRespVOList(warehouses);
        return success(list);
    }

    @GetMapping("/enabled-simple-list")
    @Operation(summary = "查询所有开启状态的仓库简单信息", description = "只返回id、name、balance字段")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:query')")
    public CommonResult<List<GoldMaterialWarehouseSimpleRespVO>> getEnabledWarehouseSimpleList() {
        List<GoldMaterialWarehouseDO> warehouses = service.getEnabledWarehouseSimpleList();
        List<GoldMaterialWarehouseSimpleRespVO> list = warehouses.stream()
                .map(warehouse -> {
                    GoldMaterialWarehouseSimpleRespVO vo = new GoldMaterialWarehouseSimpleRespVO();
                    vo.setId(warehouse.getId());
                    vo.setName(warehouse.getName());
                    vo.setBalance(warehouse.getBalance());
                    return vo;
                })
                .collect(java.util.stream.Collectors.toList());
        return success(list);
    }

    @GetMapping("/person-warehouses")
    @Operation(summary = "根据团队仓ID查询所有人员仓库")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:query')")
    public CommonResult<List<GoldMaterialWarehouseRespVO>> getPersonWarehousesByTeamWarehouseId(
            @RequestParam("teamWarehouseId") Long teamWarehouseId) {
        List<GoldMaterialWarehouseDO> warehouses = service.getPersonWarehousesByTeamWarehouseId(teamWarehouseId);
        List<GoldMaterialWarehouseRespVO> list = convertToRespVOList(warehouses);
        return success(list);
    }

    @GetMapping("/person-warehouse-count")
    @Operation(summary = "查询团队仓下的人员仓库数量")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:query')")
    public CommonResult<Long> getPersonWarehouseCountByTeamWarehouseId(
            @RequestParam("teamWarehouseId") Long teamWarehouseId) {
        Long count = service.getPersonWarehouseCountByTeamWarehouseId(teamWarehouseId);
        return success(count);
    }

    @GetMapping("/team-warehouses")
    @Operation(summary = "查询所有团队仓")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:query')")
    public CommonResult<List<GoldMaterialWarehouseRespVO>> getAllTeamWarehouses() {
        List<GoldMaterialWarehouseDO> warehouses = service.getAllTeamWarehouses();
        List<GoldMaterialWarehouseRespVO> list = convertToRespVOList(warehouses);
        return success(list);
    }

    @GetMapping("/warehouses-by-team")
    @Operation(summary = "根据团队仓ID查询相同ID的仓库")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:query')")
    public CommonResult<List<GoldMaterialWarehouseRespVO>> getWarehousesByTeamWarehouseId(
            @RequestParam(value = "teamWarehouseId", required = false) Long teamWarehouseId) {
        List<GoldMaterialWarehouseDO> warehouses;
        if (teamWarehouseId == null) {
            // 如果没有传 teamWarehouseId，返回空列表
            warehouses = new java.util.ArrayList<>();
        } else {
            warehouses = service.getWarehousesByTeamWarehouseId(teamWarehouseId);
        }
        List<GoldMaterialWarehouseRespVO> list = convertToRespVOList(warehouses);
        return success(list);
    }

    @GetMapping("/warehouses-by-teams")
    @Operation(summary = "根据团队仓ID查询本团队成员仓库")
    //@PreAuthorize("@ss.hasPermission('gold:material-warehouse:query')")
    public CommonResult<List<GoldMaterialWarehouseRespVO>> getWarehousesByTeamWarehouseIds(
            @RequestParam(value = "id", required = false) Long id) {
        List<GoldMaterialWarehouseDO> warehouses;
        if (id == null) {
            // 如果没有传 teamWarehouseId，返回空列表
            warehouses = new java.util.ArrayList<>();
        } else {
            warehouses = service.getWarehousesByTeamWarehouseIds(id);
        }
        List<GoldMaterialWarehouseRespVO> list = convertToRespVOList(warehouses);
        return success(list);
    }
}